<template>
  <el-drawer
    :visible.sync="drawer"
    size="90%"
    destroy-on-close
    :before-close="leave"
  >
    <div v-loading="isLoading">
      <!-- 基本信息 -->
      <div class="main_tile boxdq marginTop10">
        <div class="main_tile_l"><em></em>基本信息</div>
      </div>
      <div class="basic_form">
        <el-form
          :inline="true"
          :rules="rules"
          :model="basicForm"
          ref="basicForm"
          class="demo-form-inline"
          label-width="130px"
        >
          <el-form-item label="商品名称：" prop="name" v-if="!id">
            <el-input
              v-model.trim="basicForm.name"
              placeholder="商品名称"
              clearable
              :disabled="show"
              class="wid240"
              @blur.prevent="
                (val) => {
                  inputBlur(val);
                }
              "
              @keyup.enter.native="$event.target.blur"
              @change="isEdit = true"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商品名称："
            prop="name"
            :rules="rules.name"
            v-else
          >
            <el-input
              v-model.trim="basicForm.name"
              placeholder="商品名称"
              clearable
              :disabled="basicForm.standard_goods_id > 0 ? true : false"
              class="wid240"
            ></el-input>
            <!-- @input="inputName" -->
          </el-form-item>
          <el-form-item label="商品分类：" prop="category_id">
            <el-cascader
              v-model="basicForm.category_id"
              :options="options"
              :disabled="show"
              :props="defaultProps"
              class="wid240"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="商品别名：">
            <el-input
              v-model.trim="basicForm.byname"
              maxlength="20"
              placeholder="商品别名"
              show-word-limit
              class="wid150 main_limit"
              @change="isEdit = true"
            ></el-input>
            <el-checkbox v-model="basicForm.use_byname" style="margin-left: 7px"
              >使用别名</el-checkbox
            >
          </el-form-item>
          <el-form-item label="编码(SPU)：">
            <div class="box">
              <el-input
                v-model.trim="basicForm.goods_code"
                placeholder="编码"
                clearable
                :disabled="basicForm.use_code[0] == 1 ? true : false"
                class="wid240"
              ></el-input>
              <el-checkbox-group v-model="basicForm.use_code" v-if="show">
                <el-checkbox
                  :label="1"
                  class="marginLeft20"
                  @change="
                    checkboxGroup(1),
                      (basicForm.goods_code = basicForm.standard_code)
                  "
                  style="margin-right: 0"
                  >使用标准编码</el-checkbox
                >
                <el-checkbox
                  :label="0"
                  class="marginLeft20"
                  @change="checkboxGroup(0), (basicForm.goods_code = '')"
                  style="margin-right: 0"
                  >使用自定义编码</el-checkbox
                >
              </el-checkbox-group>
            </div>
          </el-form-item>
          <el-form-item label="关键词：" @change="isEdit = true">
            <el-input
              v-model.trim="basicForm.pinyin"
              placeholder="默认拼音码"
              clearable
              class="wid240"
            ></el-input>
          </el-form-item>
          <el-form-item label="采购类型：" prop="type">
            <div class="boxnr" style="width: 240px">
              <div class="maincla_lea">
                <el-select
                  v-model.trim="basicForm.purchase_relation.purchase_type"
                  placeholder="采购类型"
                  class="wid150"
                  @change="changePurchaseType"
                >
                  <el-option
                    v-for="(type_list, index) in info.type_list"
                    :key="index"
                    :label="type_list"
                    :value="parseInt(index)"
                  ></el-option>
                </el-select>
              </div>
              <el-checkbox
                v-model.trim="basicForm.specify"
                class="marginLeft10"
                style="margin-right: 0"
                >临时指定</el-checkbox
              >
            </div>
          </el-form-item>
          <el-form-item label="保质期：" class="wid240">
            <el-input
              v-model.trim="basicForm.exp"
              placeholder="保质期"
              clearable
              class="wid240"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="默认采购员："
            v-if="basicForm.purchase_relation.purchase_type == 1"
          >
            <el-select
              v-model.trim="basicForm.purchase_relation.buyer_id"
              placeholder="默认采购员"
              class="wid240"
              filterable
            >
              <el-option
                v-for="(buyer, index) in info.buyer"
                :key="index"
                :label="buyer"
                :value="parseInt(index)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="默认供应商："
            v-if="basicForm.purchase_relation.purchase_type == 2"
          >
            <el-select
              v-model.trim="basicForm.purchase_relation.supply_id"
              placeholder="默认供应商"
              class="wid240"
              filterable
            >
              <el-option
                v-for="(supplier, index) in info.supplier"
                :key="index"
                :label="supplier"
                :value="parseInt(index)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="直供供应商："
            v-if="basicForm.purchase_relation.purchase_type == 3"
          >
            <el-select
              v-model.trim="basicForm.purchase_relation.supply_id"
              placeholder="直供供应商"
              class="wid240"
              filterable
            >
              <el-option
                v-for="(direct_supply, index) in info.direct_supply"
                :key="index"
                :label="direct_supply"
                :value="parseInt(index)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <!-- sku设置 -->
      <div class="main_tile boxdq marginTop10" style="justify-content: start">
        <div class="main_tile_l"><em></em>SKU设置</div>
        <div>
          <!-- v-if="!show" 添加导入商品库隐藏按钮-->
          <!-- monitorForm.form.standard_goods_id > 0 ? false : true 编辑导入商品库隐藏按钮-->
          <el-checkbox
            style="margin-left: 30px"
            v-model="basicForm.transfer"
            @change="changeTransfer"
            :disabled="is_update == 'no' || listLenght == 1"
            >分拣时按基础单位</el-checkbox
          >
          <el-tooltip class="item" effect="dark" placement="bottom">
            <div slot="content">
              不勾选：
              适用于下单单位与分拣单位一致的商品,如:客户下单购买1瓶酱油,分拣时也按“瓶”进行分拣。（不可互调单位的商品）<br />
              勾选：
              适用于下单单位与分拣单位不一致的商品,如:客户下单购买1只鸡,分拣时需要按“斤”秤重进行分拣结算。（可互调单位的商品）
            </div>
            <svg
              style="position: relative; left: 5px; top: 2px"
              aria-hidden="true"
              class="navbar_svg new_navbar_svg"
              width="14"
              height="14"
            >
              <use xlink:href="#icon-summary_question" />
            </svg>
          </el-tooltip>
        </div>
      </div>
      <setting-table
        :rules="rules"
        :show="show"
        :transfer="basicForm.transfer"
        :info="info"
        :id="id"
        :purchase_unit="purchase_unit"
        @changeList="changeList"
        @onSubmit="onSubmit"
        ref="settingList"
      ></setting-table>
      <!-- 其他信息 -->
      <div class="main_tile boxdq marginTop10">
        <div class="main_tile_l"><em></em>其他信息</div>
      </div>
      <div class="basic_form">
        <el-form
          :inline="true"
          :rules="rules"
          :model="basicForm"
          ref="basicFrom2"
          class="demo-form-inline"
          label-width="130px"
        >
          <el-form-item label="商品排序：">
            <el-input
              v-model.trim="basicForm.sort"
              placeholder="商品排序"
              clearable
              class="wid240"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品品牌：">
            <el-autocomplete
              clearable
              @clear="bradnclearData"
              class="wid240"
              v-model="brand"
              :fetch-suggestions="querySearch"
              placeholder="请输入品牌"
              @select="brandsel"
              ref="branchSelect"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="税率：" class="wid240">
            <el-input
              v-model.trim="basicForm.tax_rate"
              placeholder="税率"
              clearable
              class="wid240"
            ></el-input>
          </el-form-item>
          <el-form-item label="产地：" class="maincla_te">
            <el-input
              v-model.trim="basicForm.madein"
              placeholder="产地"
              clearable
              class="maincla_te wid240"
            ></el-input>
          </el-form-item>
          <el-form-item label="初始数量：" class="maincla_te">
            <el-input
              v-model.trim="basicForm.init_num"
              placeholder="初始数量"
              clearable
              class="maincla_te wid240"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="统一采购单位："
            class="maincla_te"
            v-if="basicForm.transfer"
          >
            <el-select
              v-model="purchase_unit"
              placeholder="请选择"
              class="wid240"
              filterable
              :disabled="is_update == 'no'"
            >
              <el-option
                v-for="(buyer, index) in supOption"
                :key="index"
                :label="buyer.label"
                :value="buyer.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <div class="box">
            <el-form-item label="上架状态：">
              <el-switch
                v-model="basicForm.status"
                active-color="#03A98E"
                active-text="开"
                inactive-text="关"
                class="mainor_switch"
                @change="statusChange"
              ></el-switch>
            </el-form-item>
            <el-form-item label="标品：" label-width="70px">
              <el-switch
                v-model="basicForm.is_standard"
                active-color="#03A98E"
                active-text="开"
                inactive-text="关"
                class="mainor_switch"
              ></el-switch>
            </el-form-item>
          </div>
          <el-form-item label="商品标签：" class="label_ids boxha">
            <el-checkbox-group v-model="basicForm.label_ids">
              <el-checkbox
                v-for="(tag, index) in info.tag"
                :key="index"
                :label="tag.id"
                >{{ tag.title }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>
      <!-- 上传图片 -->
      <div class="main_tile boxdq">
        <div class="main_tile_l">
          <em></em>商品主图及详情
          <span>建议图片尺寸是:302*302，最多五张，主图为默认第一张</span>
        </div>
      </div>
      <div class="marginLeft20 main_upImg" v-if="!id">
        <el-upload
          :headers="{
            Authorization: getToken(),
          }"
          :action="uploadPath"
          list-type="picture-card"
          :on-success="handSuccess"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeUpload"
          :on-remove="handleRemove"
          :limit="5"
          :file-list="filelist"
        >
          <span slot="default">
            <svg
              aria-hidden="true"
              class="main_page_svg"
              width="32"
              height="27"
            >
              <use xlink:href="#icon-commodit_camera" />
            </svg>
          </span>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img :src="dialogImageUrl" alt />
        </el-dialog>
        <div class="clearfix"></div>
      </div>
      <div class="main_uqr" v-else style="position: relative">
        <div class="marginLeft10 main_upImg">
          <el-upload
            :headers="{
              Authorization: getToken(),
            }"
            :action="uploadPath"
            list-type="picture-card"
            :on-success="handSuccess"
            :before-upload="beforeUpload"
            :limit="5"
            :file-list="filelist"
            :show-file-list="false"
            ref="upload"
          >
            <span slot="default">
              <svg
                aria-hidden="true"
                class="main_page_svg"
                width="32"
                height="27"
              >
                <use xlink:href="#icon-commodit_camera" />
              </svg>
            </span>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img style="max-height: 500px;width: 100%;" :src="dialogImageUrl" alt />
          </el-dialog>
          <div class="clearfix"></div>
        </div>
        <div class="main_uqr_u">
          <ul class="boxha">
            <li
              v-for="(pics, index) in basicForm.pics"
              :key="index"
              @mouseover="pics.show = true"
              @mouseleave="pics.show = false"
            >
              <label
                class="el-upload-list__item-status-label"
                v-if="pics.main == 1"
              >
                <i class="el-icon-upload-success el-icon-check"></i>
              </label>
              <el-image fit="fill" :src="pics.url" :preview-src-list="album">
                <div slot="error" class="image-slot">
                  <img :src="puzzleImg" />
                </div>
              </el-image>
              <div class="boxdq image_po" v-if="pics.show">
                <span title="查看">
                  <svg-icon
                    icon-class="zoom-out"
                    @click.stop="handlePictureCardPreview(pics)"
                  />
                </span>
                <span title="删除">
                  <svg-icon
                    icon-class="commodity_delete"
                    @click.prevent="handleRemove(pics)"
                  />
                </span>
              </div>
            </li>
          </ul>
        </div>
      </div>
      <!-- 富文本 -->
      <div class="maincla_ed marginLeft10">
        <Editor
          api-key="vl7byj8kh7hyvvi6o7137s7khcpfsp762987dlnbcd93u37a"
          v-model="basicForm.detail"
          :init="init"
        ></Editor>
      </div>
      <div class="clearfix"></div>
      <!-- 底部 -->
      <div class="newConBox_p200 paddingBottom10" id="newConBox">
        <div class="newConBox_h32">
          <div :class="['boxdq newConBox on']" style="z-index: 100">
            <div class="mainor_prl">
              <el-button
                type="primary"
                @click="preservation(1)"
                v-repeatClick
                v-if="!id"
                >保存并继续添加</el-button
              >
              <el-button
                class="reset marginLeft10"
                type="primary"
                @click="preservation(2)"
                v-repeatClick
                :style="{ color: id ? '' : '' }"
                >保存并返回列表</el-button
              >
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script>
const form = {
  name: "",
  byname: "",
  category_id: [],
  pid: "",
  pinyin: "",
  goods_code: "",
  brand: "",
  pics: [],
  pic: "",
  sort: 0,
  describe: "",
  use_byname: false,
  nonstandard_goods_id: "",
  use_code: [0],
  standard_goods_id: 0,
  standard_code: "",
  status: false,
  is_recommend: true,
  is_standard: false,
  specify: true,
  label_ids: [],
  detail: "",
  transfer: false,
  init_num: '', //  初始数量
  // 保质期
  exp: "",
  // 产地
  madein: "",
  tax_rate: "", //税率
  purchase_relation: {
    purchase_type: 1,
    buyer_id: "",
    supply_id: "",
  },
};
import Editor from "@tinymce/tinymce-vue";
import settingTable from "./settingTable";
import init from "./init";
import { uploadPath, images_delete, puzzleImg } from "@/api/currency";
import { apiUrl, objKeySort, Md5, packApi } from "@/utils/public";
import {
  goods_base,
  goods_add,
  goods_check,
  goods_info,
  goods_edit,
} from "@/api/commodity/commodityList";
import { recursion, category } from "@/utils/index";
import rules from "@/rules/commodity/commodity_List_add";
import { mapGetters } from "vuex";
export default {
  components: {
    Editor,
    settingTable,
  },
  computed: {
    ...mapGetters(["avatar"]),
  },
  data() {
    return {
      isLoading: false,
      // 抽屉状态
      drawer: false,
      // 验证
      rules,
      // 商品名称标准库
      show: false,
      isEdit: false,
      // 基本信息
      basicForm: {
        init_num: '', //  初始数量
        name: "", // 名称
        byname: "", // 别名
        category_id: [], // 分类
        pid: "",
        pinyin: "",
        goods_code: "",
        nonstandard_goods_id: "",
        brand: "", // 商品品牌
        pics: [],
        pic: "",
        sort: 0, // 排序
        describe: "",
        use_byname: false,
        use_code: [0],
        standard_goods_id: 0,
        standard_code: "",
        status: false,
        is_recommend: true,
        is_standard: false,
        specify: true,
        label_ids: [],
        detail: "",
        transfer: false,
        // 保质期
        exp: "",
        tax_rate: "",
        // 产地
        madein: "",
        purchase_relation: {
          purchase_type: 1,
          buyer_id: "",
          supply_id: "",
        },
      },
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
      },
      // 富文本
      init,
      // 信息
      info: {
        unit: [],
      },
      // 上传图片
      filelist: [],
      uploadPath,
      dialogImageUrl: "",
      dialogVisible: false,
      // 监听滚动
      // searchBarFixed: false,
      //sku是否全部关闭
      sku_all_status: false,
      // 统一采购单位
      supOption: [],
      purchase_unit: "",
      brand: "", // 商品品牌
      id: "", // 编辑id
      album: [], // 图片数组
      puzzleImg,
      is_update: "", // 是否可以修改分拣单位 no不可以修改
      listLenght: null, // sku的长度
    };
  },
  watch: {
    drawer(val) {
      if (!val) {
        // 离开页面的是将表单数据清空
        this.basicForm = JSON.parse(JSON.stringify(form));
        this.show = false;
        this.isEdit = false;
        this.filelist = [];
        this.id = "";
        this.brand = "";
        this.is_update = "";
        this.isLoading = false;
      }
    },
  },
  methods: {
    // 打开抽屉
    open(data) {
      this.basicForm.detail = "";
      if (data) {
        this.id = data;
        this.isLoading = true;
        // 下拉信息
        this.goods_base().then(() => {
          // 编辑回填
          this.goods_info();
        });
      } else {
        // 下拉信息
        this.goods_base();
      }
      this.drawer = true;
    },
    // 基本信息
    goods_info() {
      let data = packApi({ id: this.id });
      goods_info(data).then((res) => {
        if (res.errcode == 0) {
          this.backfill(res.data); // 回填
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 回填
    backfill(data, type) {
      let use_code = [];
      use_code.push(parseInt(data.info.use_code));
      data.info.spu.map((e, index) => {
        e.status = e.status == 1 ? true : false;
        e.is_can = "";
        e.is_unit = "";
        e.no_can = "";
        e.no_unit = "";
        e.spu_title = "";
        e.spu_unit = "";
        let isExist = false;
        let attrIsExit = false;
        // 如果是可互调
        if (data.info.transfer > 0) {
          this.info.unit.map((unit) => {
            if (unit.id == e.spu_name) {
              isExist = true;
              e.spu_title = unit.title;
              e.spu_unit = unit.title;
              return;
            }
          });
          e.spu_name = isExist ? parseInt(e.spu_name) : "";
        } else if (data.info.transfer == 0) {
          this.info.attribute.map((unit) => {
            if (unit.id == e.spu_name) {
              attrIsExit = true;
              e.spu_title = unit.title;
              return;
            }
          });
          this.info.unit.map((u) => {
            if (u.id == e.unit) {
              attrIsExit = true;
              e.spu_unit = u.title;
              return;
            }
          });
          e.spu_name = attrIsExit ? parseInt(e.spu_name) : "";
        }
        if (index == 0) {
          if (!isExist) {
            e.disabled = false;
          } else {
            e.disabled = true;
          }
        }
        if (e.standard_spu_id == 0) {
          e.disabled = false;
        } else {
          e.disabled = true;
        }
        e.transfer_unit = e.transfer_unit ? parseInt(e.transfer_unit) : "";
        e.down = false;
      });
      const arry = data.info.images.map((a) => ({
        name: "",
        path: a.path,
        url: this.avatar.domain + "/" + a.path,
        id: a.id,
        main: a.main,
        show: false,
      }));
      this.basicForm.use_code = use_code;
      this.basicForm.init_num = data.info.init_num;
      this.basicForm.name = data.info.name;
      this.basicForm.byname = data.info.byname;
      this.basicForm.category_id = [data.info.pid, data.info.category_id];
      this.basicForm.pid = data.info.pid;
      this.basicForm.pinyin = data.info.pinyin;
      this.basicForm.goods_code = data.info.goods_code;
      this.basicForm.brand = data.info.brand ? parseInt(data.info.brand) : "";
      //根据id去匹配商品品牌
      let id = this.basicForm.brand;
      this.info.brand.map((e) => {
        if (id == e.id) {
          this.brand = e.title;
        }
      });

      if (data.info.purchase_relation.length != 0) {
        const buyer = this.info.buyer ? Object.keys(this.info.buyer) : [];
        const supplier = this.info.supplier ? Object.keys(this.info.supplier) : [];
        const direct_supply = this.info.direct_supply ? Object.keys(this.info.direct_supply) : [];
        this.basicForm.purchase_relation.buyer_id =
          data.info.purchase_relation[0].buyer_id == 0
            ? ""
            : parseInt(data.info.purchase_relation[0].buyer_id);

        let supply_type = data.info.purchase_relation[0].supply_type;
        if (supply_type == 1) {
          this.basicForm.purchase_relation.purchase_type = parseInt(
            data.info.purchase_relation[0].bind_type
          );
        } else if (supply_type == 2) {
          this.basicForm.purchase_relation.purchase_type = parseInt(3);
        }
        this.basicForm.purchase_relation.supply_id =
          data.info.purchase_relation[0].supplier_id == 0
            ? ""
            : parseInt(data.info.purchase_relation[0].supplier_id);

        let buyer_id = String(this.basicForm.purchase_relation.buyer_id);
        let supplier_id = String(this.basicForm.purchase_relation.supply_id);

        if (!buyer.includes(buyer_id)) {
          this.basicForm.purchase_relation.buyer_id = "";
        }
        if ((!direct_supply.includes(supplier_id) && supply_type == 2) || (!supplier.includes(supplier_id) && supply_type == 1)) {
          this.basicForm.purchase_relation.supplier_id = "";
        }
      }
      this.basicForm.pics = JSON.parse(JSON.stringify(arry));
      this.filelist = JSON.parse(JSON.stringify(arry));
      this.basicForm.pic = data.info.pic;
      this.basicForm.sort = data.info.sort;
      // 产地
      this.basicForm.madein = data.info.madein;
      this.basicForm.exp = data.info.exp;
      this.basicForm.tax_rate = data.info.tax_rate;
      this.basicForm.describe = data.info.describe;
      this.basicForm.specify = data.info.specify == 1 ? true : false;
      this.basicForm.status = data.info.status == 1 ? true : false;
      this.basicForm.is_recommend = data.info.is_recommend == 1 ? true : false;
      this.basicForm.is_standard = data.info.is_standard == 1 ? true : false;
      this.basicForm.use_byname = data.info.use_byname == 1 ? true : false;
      this.basicForm.label_ids = data.info.label_ids
        ? data.info.label_ids.split(",").map((e) => parseInt(e))
        : [];

      this.basicForm.transfer = data.info.transfer == 1 ? true : false;
      this.$refs.settingList.setList(data.info.spu);
      this.basicForm.detail = data.info.detail;
      this.basicForm.standard_goods_id = data.info.standard_goods_id;
      this.basicForm.standard_code = data.info.standard_code;
      this.is_update = data.info.is_update;
      this.purchase_unit = data.info.purchase_unit ? parseInt(data.info.purchase_unit) : "";
      this.isLoading = false;
    },
    // 子组件list数据改变
    changeList(val) {
      const num = val.reduce((count, item) => count + (item.status ? 0 : 1), 0);
      num == val.length
        ? ((this.basicForm.status = false), (this.sku_all_status = true))
        : (this.sku_all_status = false);
      this.supOption = [];
      val.forEach((item) => {
        // 因为编辑和添加用的不是同一个字段 添加-spu_name_title 编辑-spu_title
        if (item.spu_name_title && !this.id) {
          const { spu_name_title: label, spu_name } = item;
          this.supOption.push({ label, id: spu_name });
        } else if (item.spu_title && this.id) {
          const { spu_title: label, spu_name } = item;
          this.supOption.push({ label, id: spu_name });
        }
      });
      
      // 如果没有选择才默认第一个
      if (!this.purchase_unit && this.supOption.length) {
        this.purchase_unit = this.supOption[0].id || "";
      }
      if(this.supOption.length){
        // 如果把统一单位删除了就赋值里面的第一个
        let flag = this.supOption.some(item=>item.id==this.purchase_unit)
        if(!flag) this.purchase_unit = this.supOption[0].id
      }else{
        // 如果没有值了就清空
        this.purchase_unit = "";
      }
      this.listLenght = val.length;
    },
    // 可互调不可互调切换
    changeTransfer(val) {
      // 通知子组件切换
      this.$refs.settingList.changeTransfer(val);
      // 将统一采购单位值清空
      this.purchase_unit = "";
    },
    // 校验
    preservation(id) {
      this.$refs["basicForm"].validate((valid) => {
        if (valid) {
          // 调用子组件校验
          this.$refs.settingList.inspect(id);
        }
      });
    },
    // 保存
    onSubmit({ dataList, id }) {
      let dage = false;
      dage = dataList.every((ii) => {
        return (
          (ii.spu_title,
          ii.spu_unit,
          ii.package_num,
          ii.purchase_price,
          ii.market_price) != ""
        );
      });
      if (!dage) {
        this.$message.error("SKU“必填项不能为空”");
        return;
      }
      if(!dataList.every(item => parseFloat(item.package_num) > 0)) return this.$message.error("互调比必须大于0");
      let arry = JSON.parse(JSON.stringify(this.basicForm));
      dataList.forEach((i) => {
        delete i.demo_designated_inventory;
        delete i.is_update;
      });
      let sz = JSON.parse(JSON.stringify(dataList));
      let list = [];
      // 根据添加/编辑处理数据
      if (this.id) {
        list = sz.map((a) => {
          a.transfer_unit = a.transfer_unit ? a.transfer_unit : 0;
          let {
            down,
            standard_goods_id,
            disabled,
            is_can,
            no_can,
            is_unit,
            no_unit,
            spu_title,
            spu_unit,
            unit_name,
            spu_name_title,
            ...sz
          } = a;
          return { ...sz };
        });
        delete this.basicForm.nonstandard_goods_id;
      } else {
        list = sz.map((a) => {
          a.transfer_unit = a.transfer_unit ? a.transfer_unit : 0;
          let {
            down,
            standard_goods_id,
            spu_name_title,
            unit_name,
            spu_title,
            spu_unit,
            ...sz
          } = a;
          return { ...sz };
        });
      }
      if (arry.use_byname) {
        if (!arry.byname) {
          this.$message.warning("您勾选了使用别名，请填入");
          return;
        }
      }
      arry.use_code = arry.use_code[0];
      arry.specify = arry.specify ? 1 : 0;
      arry.status = arry.status ? 1 : 0;
      arry.use_byname = arry.use_byname ? 1 : 0;
      arry.is_recommend = arry.is_recommend ? 1 : 0;
      arry.is_standard = arry.is_standard ? 1 : 0;
      arry.pid = arry.category_id[0];
      arry.purchase_relation.buyer_id = arry.purchase_relation.buyer_id
        ? arry.purchase_relation.buyer_id
        : 0;
      arry.purchase_relation.supply_id = arry.purchase_relation.supply_id
        ? arry.purchase_relation.supply_id
        : 0;
      arry.category_id = category(arry.category_id);
      arry.label_ids =
        arry.label_ids.length != 0 ? arry.label_ids.join(",") : "";
      arry.pic = arry.pics[0] ? arry.pics[0].path : "";
      arry.pics =
        arry.pics.length != 0 ? arry.pics.map((p) => p.path).join(",") : "";

      // arry.images =
      //   arry.pics.length != 0 ? arry.pics.map((p) => p.path).join(",") : "";
      arry.purchase_relation = JSON.stringify(arry.purchase_relation);
      arry.transfer = arry.transfer ? 1 : 0;
      arry.purchase_unit = this.purchase_unit;
      if (!this.id) {
        let data = packApi({...arry , list: JSON.stringify(list)});
        goods_add(data).then((res) => {
          if (res.errcode == 0) {
            this.$message({
              message: "新增成功",
              type: "success",
            });
            // id为1是保存并继续添加
            if (id == 1) {
              this.drawer = false;
              this.$nextTick(() => {
                this.drawer = true;
                this.$emit("getList");
              });
            } else {
              this.drawer = false;
              this.$emit("pageReload");
            }
          } else {
            this.$message.error(res.errmsg);
          }
        });
      } else {
        let data = packApi({...arry ,list: JSON.stringify(list), id: this.id });
        goods_edit(data).then((res) => {
          if (res.errcode == 0) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            if (id == 2) {
              this.isEdit = false;
              this.drawer = false;
              this.$emit("pageReload");
            }
          } else {
            this.$message.error(res.errmsg);
          }
        });
      }
    },
    //采购类型
    changePurchaseType($event) {
      this.basicForm.purchase_relation.supply_id = "";
      this.basicForm.purchase_relation.buyer_id = "";
    },
    // 焦点离开商品
    inputBlur(val) {
      if (val.target.value != "") {
        let data = Object.assign(
          {
            sign: Md5(
              objKeySort(
                Object.assign(apiUrl().name, { name: val.target.value })
              ) + apiUrl().appsecret
            ),
          },
          apiUrl().name,
          { name: val.target.value }
        );
        goods_check(data).then((res) => {
          if (res.errcode == 0) {
          } else if (res.errcode == 40017) {
            // this.$alert("导入标准库商品", "提示", {
            //   showClose: false,
            //   confirmButtonText: "确定",
            //   callback: (action) => {
            //     this.show = true;
            //     this.standard(res.data, 1);
            //   },
            // }).catch(() => {});
          } else if (res.errcode == 40018) {
            // this.$confirm("导入非标准库商品", "提示", {
            //   confirmButtonText: "确定",
            //   cancelButtonText: "取消",
            //   type: "warning",
            // })
            //   .then(() => {
            //     this.standard(res.data, 2);
            //   })
            //   .catch(() => {});
          } else {
            this.$message.error(res.errmsg);
          }
        });
      }
    },
    // 导入标准库/非标准库的信息回填
    standard(data, type) {
      let arry = [];
      let use_code = [];
      use_code.push(parseInt(data.info.use_code));
      data.info.spu.map((e) => {
        e.status = e.status == 1 ? true : false;
        e.spu_name = parseInt(e.spu_name);
        e.transfer_unit = e.transfer_unit ? parseInt(e.transfer_unit) : "";
        e.down = false;
      });
      if (data.info.pics) {
        data.info.pics.split(",").map((e) => {
          arry.push({ name: "", path: e, url: data.domain + e });
        });
      }
      this.basicForm.use_code = use_code;
      this.basicForm.name = data.info.name;
      this.basicForm.byname = data.info.byname;
      this.basicForm.category_id = [data.info.pid, data.info.category_id];
      this.basicForm.pid = data.info.pid;
      this.basicForm.pinyin = data.info.pinyin;
      this.basicForm.goods_code = data.info.goods_code;
      // this.basicForm.brand = parseInt(data.info.brand);
      this.basicForm.pics = JSON.parse(JSON.stringify(arry));
      this.filelist = JSON.parse(JSON.stringify(arry));
      this.basicForm.pic = data.info.pic;
      this.basicForm.sort = data.info.sort;
      this.basicForm.describe = data.info.describe;
      this.basicForm.specify = data.info.specify == 1 ? true : false;
      this.basicForm.status = data.info.status == 1 ? true : false;
      this.basicForm.is_recommend = data.info.is_recommend == 1 ? true : false;
      this.basicForm.is_standard = data.info.is_standard == 1 ? true : false;
      this.basicForm.use_byname = data.info.use_byname == 1 ? true : false;
      this.basicForm.label_ids = data.info.label_ids
        ? data.info.label_ids.split(",").map((e) => parseInt(e))
        : [];

      this.basicForm.transfer = data.info.transfer == 1 ? true : false;
      this.$refs.settingList.setList(data.info.spu);
      this.basicForm.detail = data.info.detail;
      this.basicForm.standard_code = data.info.standard_code;
      if (type == 1) {
        this.basicForm.standard_goods_id = data.info.id;
        this.basicForm.use_code = [1];
        this.basicForm.goods_code = data.info.standard_code;
      }
      if (type == 2) {
        this.basicForm.nonstandard_goods_id = data.info.id;
      }
    },
    // 下拉信息
    goods_base() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
      );
      if (this.id) {
        return new Promise((resolve, reject) => {
          goods_base(data).then((res) => {
            if (res.errcode == 0) {
              this.options = recursion(res.data.category);
              res.data.brand.map((e) => {
                e.value = e.title;
              });
              res.data.attribute.map((c) => {
                c.value = c.title;
              });
              res.data.unit.map((d) => {
                d.value = d.title;
              });
              this.info = res.data;
              resolve();
            } else {
              this.$message.error(res.errmsg);
            }
          });
        });
      } else {
        goods_base(data).then((res) => {
          if (res.errcode == 0) {
            this.options = recursion(res.data.category);
            res.data.brand.map((e) => {
              e.value = e.title;
            });
            res.data.attribute.map((c) => {
              c.value = c.title;
            });
            res.data.unit.map((d) => {
              d.value = d.title;
            });
            this.info = res.data;
          } else {
            this.$message.error(res.errmsg);
          }
        });
      }
    },
    // 上架状态
    statusChange() {
      if (this.sku_all_status) {
        this.$message.warning("请至少开启一个SKU");
        this.basicForm.status = false;
      }
    },
    //品牌搜索
    querySearch(queryString, cb) {
      let restaurants = this.info.brand;
      let results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    //品牌搜搜清空事件
    bradnclearData() {
      this.brand = "";
      this.basicForm.brand = "";
      this.$refs.branchSelect.activated = true;
    },
    //过滤方法
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    //选择事件方法
    brandsel(item) {
      this.basicForm.brand = item.id;
    },
    // 标准编码
    checkboxGroup(val) {
      this.basicForm.use_code = [];
      this.basicForm.use_code.push(val);
    },
    // 上传图片-删除
    handleRemove(file) {
      if (this.id) {
        this.$confirm("确定删除图片？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            let isupdata = this.filelist.findIndex(
              (item) => item.path == file.path
            );
            if (isupdata != -1) {
              let data = Object.assign(
                {
                  sign: Md5(
                    objKeySort(Object.assign(apiUrl().name, { id: file.id })) +
                      apiUrl().appsecret
                  ),
                },
                apiUrl().name,
                { id: file.id }
              );
              images_delete(data).then((res) => {
                if (res.errcode == 0) {
                  const i = this.basicForm.pics.findIndex(
                    (item) => item.path == file.path
                  );
                  this.basicForm.pics.splice(i, 1);
                  this.$refs.upload.uploadFiles.splice(i, 1);
                } else {
                  this.$message.error(res.errmsg);
                }
              });
            } else {
              try {
                const i = this.basicForm.pics.findIndex(
                  (item) => item.path == file.path
                );
                if (i >= 0) {
                  this.basicForm.pics.splice(i, 1);
                  this.$refs.upload.uploadFiles.splice(i, 1);
                }
              } catch (error) {
                console.log(error);
              }
            }
          })
          .catch((e) => {});
      } else {
        const i = this.basicForm.pics.findIndex(
          (item) => item.path == file.path
        );
        this.basicForm.pics.splice(i, 1);
      }
    },
    // 上传图片-查看
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传图片-成功
    handSuccess(res, file, fileList) {
      this.isEdit = true;
      if (this.id) {
        this.basicForm.pics.push({
          name: "",
          main: 0,
          path: res.data.path,
          url: res.data.src,
          show: false,
        });
        this.album.push(res.data.src);
      } else {
        this.basicForm.pics.push({
          name: "",
          path: res.data.path,
          url: res.data.src,
        });
      }
    },
    // 上传图片前
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isLt2M) {
        this.$message.error("上传商品图片大小不能超过 1MB!");
      }
      return isLt2M;
    },
    // 数据修改了离开确认
    leave() {
      if (this.isEdit) {
        setTimeout(() => {
          this.$confirm(
            "您已经有数据操作，离开页面系统不会保存您的操作，确定离开吗？",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(() => {
              this.drawer = false;
            })
            .catch(() => {});
        }, 200);
      } else {
        this.drawer = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
/deep/.el-drawer__body {
  padding-left: 20px;
}
.basic_form {
  display: flex;
  flex-wrap: wrap;
  width: 70%;
  margin: 10px;
  /deep/.el-form .el-form-item--small.el-form-item {
    margin-bottom: 20px !important;
  }
}

.maincla_ed {
  margin-top: 20px;
  margin-left: 20px;
  width: 66%;
}
.image_po {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 92;
  width: 100%;
  height: 100%;
  padding-left: 15px;
  border-radius: 4px;
  padding-right: 15px;
  background: $subMenuHover;
  span {
    &:first-child {
      .svg-icon {
        font-size: $font_18;
      }
    }
  }
  .svg-icon {
    font-size: $font_16;
    color: $white;
    &:hover {
      cursor: pointer;
    }
  }
}
</style>